import { ChangeEvent, useState } from 'react';
import { List, ListItem, ListItemText } from '@material-ui/core';

import Input from './Input';
import Button from './Button';

function InputRow(prop: { addTodoItem: (todo: string) => void }) {
  const [input, setInput] = useState('');

  function addTodo() {
    prop.addTodoItem(input);
    setInput('');
  }

  return (
    <form>
      <Input
        value={input}
        onChange={(event: ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => setInput(event.target.value)}
      />
      <Button onClick={addTodo} color="primary" variant="outlined">
        Add Item
      </Button>
    </form>
  );
}

export function TodoList() {
  const [todos, setTodos] = useState(['Improve JS skills 💪', 'Pet dog 🐶']);

  function addTodoItem(todo: string) {
    todo.length && setTodos([...todos, todo]);
  }

  function removeTodoItem(index: number) {
    todos.splice(index, 1);
    setTodos([...todos]);
  }

  return (
    <div className="todo-list">
      <h1>Todo Items</h1>
      <InputRow addTodoItem={addTodoItem} />
      <List>
        {todos.map((todo, i) => (
          <ListItem key={`${todo}-${i}`}>
            <ListItemText>{todo}</ListItemText>
            <Button color="secondary" onClick={() => removeTodoItem(i)}>
              Remove
            </Button>
          </ListItem>
        ))}
      </List>
    </div>
  );
}
